<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model.trim="query.customerName" clearable placeholder="请输入客户名称" @keyup.enter.native="getInfo" />
      <el-date-picker v-model="q_p_formDate1" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange"
        range-separator="-" start-placeholder="起始日期" end-placeholder="终止日期" @change="q_p_selectTimecreate" />
      <el-button type="primary" icon="el-icon-search" @click="getInfo">
        {{ $t('table.search') }}
      </el-button>
      <el-button @click="handleExport" type="primary" icon="el-icon-download">
        {{ $t("table.export") }}
      </el-button>
    </div>
    <el-table :data="tableData" row-key="index" highlight-current-row border
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="customerCode" label="客户编码" />
      <el-table-column prop="customerName" label="客户名称" />
      <el-table-column prop="prePrice" label="期初应收款" />
      <el-table-column prop="currPrice" label="本期增加应收款" />
      <el-table-column prop="titleName" label="本期收回应收款" />
      <el-table-column prop="paymentMode" label="期末应收款30天">
        <template slot-scope="{row}">
          {{ row.paymentMode == 1 ? row.prePrice + row.currPrice : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="paymentMode" label="期末应收款60天">
        <template slot-scope="{row}">
          {{ row.paymentMode == 2 ? row.prePrice + row.currPrice : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="paymentMode" label="期末应收款90天">
        <template slot-scope="{row}">
          {{ row.paymentMode == 3 ? row.prePrice + row.currPrice : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="paymentMode" label="期末应收款合计">
        <template slot-scope="{row}">
          {{ row.prePrice + row.currPrice }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">明细</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog width="70%" @closed="handleClose" :close-on-click-modal="false" :visible.sync="dialogVisible" title="明细">
      <el-button style="margin-bottom:10px" type="primary" icon="el-icon-plus" @click="handleClick">
        发货单绑定发票
      </el-button>
      <el-button style="margin-bottom:10px" type="primary" icon="el-icon-download" @click="handleDetailExport">
        明细导出
      </el-button>
      <el-table :data="fundTableData" row-key="id" highlight-current-row border
        @selection-change="handleSelectionChange" :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }" ref="multipleTable">
        <el-table-column type="selection" width="55" :selectable="selectableStatus" />
        <el-table-column prop="customerCode" label="客户代码" />
        <el-table-column prop="customerName" label="客户" />
        <el-table-column prop="businessNo" label="订单号" />
        <el-table-column prop="materialName" label="商品名称" />
        <el-table-column prop="inoutStoreNum" label="出库数量" />
        <el-table-column prop="unitPrice" label="金额（不含税）" />
        <el-table-column prop="price" label="金额（含税）" />
        <el-table-column prop="replyTime" label="出库日期">
          <template slot-scope="{row}">
            <span>{{ row.replyTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="invoiceId" label="绑定状态">
          <template slot-scope="{row:{invoiceId}}">
            <el-tag :type="invoiceId ? 'success' : 'danger'">{{ invoiceId ? '已' : '未' }}绑定</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog @closed="fundHandleClose" :close-on-click-modal="false" :visible.sync="fundDialogVisible" title="发票信息">
      <el-form ref="fundRuleForm" :model="fund" label-width="140px" :rules="fundRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票号" prop="invoiceCode">
              <el-input v-model.trim="fund.invoiceCode" placeholder="请输入发票号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发票日期" prop="invoiceDate">
              <el-date-picker style="width: 100%;" v-model="fund.invoiceDate" type="date" value-format="yyyy-MM-dd"
                placeholder="选择发票日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="我方抬头" prop="ourHeaderId">
              <el-select style="width: 100%;" v-model="fund.ourHeaderId" filterable placeholder="请选择客户抬头">
                <el-option v-show="item.type == 0" v-for="item in userList" :key="item.id"
                  :label="`${item.name}/${item.taxpayer}/${item.bankDetail}`" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户抬头" prop="sellHeaderId">
              <el-select style="width: 100%;" v-model="fund.sellHeaderId" filterable placeholder="请选择供应商抬头">
                <el-option v-show="item.type == 1" v-for="item in userList" :key="item.id"
                  :label="`${item.name}/${item.taxpayer}/${item.bankDetail}`" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="税额" prop="taxAmount">
              <el-input v-model.trim="fund.taxAmount" :disabled="true" placeholder="请输入税额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总金额（不含税）" prop="amount">
              <el-input :disabled="true" v-model.trim="fund.amount" placeholder="请输入总金额（不含税）" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="税率" prop="taxRate">
              <el-input :disabled="true" v-model.trim="fund.taxRate" placeholder="请输入税率" />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="总金额（含税）" prop="totalAmount">
              <el-input :disabled="true" v-model.trim="fund.totalAmount" placeholder="请输入总金额（含税）" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="fundDialogVisible = false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="fundConfirm">{{ $t('permission.save') }}</el-button>
      </div>
    </el-dialog>
    <!-- <el-pagination
      style="margin-top:20px;"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    /> -->
  </div>
</template>
<script>
import { accReceivable, accBindInvoice, accExport1, accDetail1Export } from '@/api/evaluatePerformance'
import { sysInvoiceHeaderAll } from '@/api/invoice'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { downfile } from '@/utils'

export default {
  name: 'Customerforecast',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      dialogVisible: false,
      query: {
        pageIndex: 1,
        pageSize: 20,
        startDate: '',
        endDate: ''
      },
      headerQuery: {},
      userList: [],
      tableData: [],
      q_p_formDate1: [],
      fundTableData: [],
      selectedList: [],
      fundDialogVisible: false,
      fund: {},
      fundRules: {
        invoiceCode: [
          { required: true, message: '请输入发票号', trigger: 'blur' }
        ],
        invoiceDate: [
          { required: true, message: '请输入选择发票日期', trigger: 'change' }
        ],
        ourHeaderId: [
          { required: true, message: '请输入客户抬头', trigger: 'blur' }
        ],
        sellHeaderId: [
          { required: true, message: '请输入供应商抬头', trigger: 'blur' }
        ],
        taxAmount: [
          { required: true, message: '请输入税额', trigger: 'blur' }
        ],
        taxRate: [
          { required: true, message: '请输入税率', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入金额（不含税）', trigger: 'blur' }
        ],
        totalAmount: [
          { required: true, message: '请输入金额（含税）', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getday()
    this.getUserPage()
  },
  methods: {
    async handleDetailExport() {
      try {
        // const { query } = this.query
        const formData = new FormData()
        formData.append('wmsStoreAppliesJson', JSON.stringify(this.fundTableData))
        await accDetail1Export(formData)
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile('应收明细.xlsx', err);
          }
        }
      }
    },
    async handleExport() {
      try {
        const formData = new FormData()
        for(let key in this.query){
          formData.append(key,this.query[key])
        }
        await accExport1(formData)
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile('应收.xlsx', err);
          }
        }
      }
    },
    selectableStatus(row) {
      return !row.invoiceId
    },
    async getUserPage() {
      this.userList = await sysInvoiceHeaderAll(this.headerQuery)
    },
    handleClose() {
      this.selectedList = []
      this.$refs.multipleTable.clearSelection();
    },
    fundHandleClose() {
      this.fund = {}
      this.$refs['fundRuleForm'].resetFields()
    },
    fundConfirm() {
      this.$refs['fundRuleForm'].validate(async (valid) => {
        if (valid) {
          await accBindInvoice({
            wmsStoreApplyIds: this.selectedList.map(type => type.id).join(','),
            accSellInvoice: this.fund
          })
          this.getInfo()
          this.$message.success('绑定成功！')
          this.fundDialogVisible = false
          this.dialogVisible = false
        }
      })
    },
    handleSelectionChange(e) {
      this.selectedList = []
      this.checked = e
      e.forEach((item) => {
        this.selectedList.push(item)
      })
    },
    handleClick() {
      if (!this.selectedList.length) {
        this.$message.warning('请至少选择一条订单')
        return
      }
      this.fund.amount = this.selectedList.reduce((prev, cur, index, arr) => {
        return prev + cur.unitPrice
      }, 0)
      this.fund.totalAmount = this.selectedList.reduce((prev, cur, index, arr) => {
        return prev + cur.price
      }, 0)
      this.fund.taxAmount = this.fund.totalAmount * 1 - this.fund.amount * 1
      this.fundDialogVisible = true
    },
    getday(bool) {
      const currDate = new Date().toLocaleDateString()// 2020/11/6
      const arrs = currDate.split('/')
      const arrs1 = arrs.join('-')
      const yy = parseInt(arrs[0]);
      const mm = parseInt(arrs[1]);
      const dd = parseInt(arrs[2]);
      const pdStr = new Date(yy, mm - 2, dd).toLocaleDateString().split('/').join('-');
      this.query.startDate = pdStr
      this.query.endDate = arrs1
      this.q_p_formDate1 = [pdStr, arrs1]
      if (!bool) this.getInfo()
    },
    q_p_selectTimecreate(val) {
      if (val) {
        this.query.startDate = val[0]
        this.query.endDate = val[1]
      } else {
        this.$nextTick(() => {
          this.getday(true)
        })
      }
    },
    handleUpdate(row) {
      this.fundTableData = row.wmsStoreApplies || []
      this.dialogVisible = true
    },
    handleSizeChange(size) {
      this.query.pageSize = size
    },
    handleCurrentChange(currentPage) {
      this.query.pageIndex = currentPage
    },
    async getInfo() {
      const data = await accReceivable(this.query)
      this.tableData = []
      for (let key in data) {
        this.tableData.push(data[key])
      }
    }
  }
}

</script>
<style>
.item {
  padding: 10px 30px;
  border: 0.5px solid #dfe6ec;

}

.name {

  font-weight: bold;
}

.item1 {
  /*color:#999;*/
  /*font-size:14px;*/
}
</style>
